#include <iostream>
#include <string>
#include <fstream>
#include "contacts.pb.h"

void PrintContacts(contacts2::Contacts &contacts)
{
    for (int i = 0; i < contacts.contacts_size(); i++)
    {
        std::cout << "------------------联系人" << i + 1 << "------------------" << std::endl;
        const contacts2::PeopleInfo &people = contacts.contacts(i);
        std::cout << "联系人姓名：" << people.name() << std::endl;
        std::cout << "联系人年龄: " << people.age() << std::endl;
        for (int j = 0; j < people.phone_size(); j++)
        {
            const contacts2::PeopleInfo_Phone &phone = people.phone(j);
            std::cout << "联系人电话: " << j + 1 << " " << phone.number();

            std::cout << "  (" << phone.PhoneType_Name(phone.type()) << ")" << std::endl;
        }

        if (people.has_data() && people.data().Is<contacts2::Address>())
        {
            contacts2::Address address;
            people.data().UnpackTo(&address);
            if (!address.home_address().empty())
            {
                std::cout << "联系人的家庭住址为：" << address.home_address() << std::endl;
            }
            if (!address.unit_address().empty())
            {
                std::cout << "联系人的家庭住址为：" << address.unit_address() << std::endl;
            }
        }

        switch (people.other_contact_case())
        {
        case contacts2::PeopleInfo::kQq:
            std::cout << "联系人 qq: " << people.qq() << std::endl;
            break;
        case contacts2::PeopleInfo::kWechat:
            std::cout << "联系人 wechat: " << people.wechat() << std::endl;
            break;
        default:
            break;
        }

        if (people.remark_size())
        {
            std::cout << "备注信息: " << std::endl;

            for (auto it = people.remark().cbegin(); it != people.remark().cend(); it++)
            {
                std::cout << "     " << it->first << ": " << it->second << std::endl;
            }
        }
    }
}

int main()
{
    contacts2::Contacts contacts;
    // 读取本地已存在的通讯录文件
    std::fstream intput("contacts.bin", std::ios::in | std::ios::binary);
    if (!contacts.ParseFromIstream(&intput))
    {
        std::cout << "ParseFromIstream Failed!" << std::endl;
        intput.close();
        return -1;
    }

    // 打印通讯录列表
    PrintContacts(contacts);

    return 0;
}